import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Select, DatePicker, Badge } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { QueryBigChargeOrderListParams, BigChargeOrder, BigChargeOrderStatus, BigChargeOrderInfoType, BigChargeOrderPayType } from './services';
import { queryBigChargeOrderList } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StationSelect from '@/components/StationSelect';
import ColumnDesc from '@/components/ColumnDesc';
import { history } from '@umijs/max'
import { EquipmentType } from '@/pages/station/stubList/services';
import dayjs from 'dayjs';
import { jump2target } from '@/utils/common';

const BigChargeOrderPage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<QueryBigChargeOrderListParams>({
    pageNum: 1, pageSize: 10, 
    beginTime: dayjs().subtract(31, 'day').format('YYYY-MM-DD HH:mm:ss'), 
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  const list = useRequest(() => queryBigChargeOrderList(searchParams), {
    refreshDeps: [searchParams], debounceWait: 10,
  })

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      id: formValues.id,
      status: formValues.status,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stubId: formValues.stubId,
      equipmentId: formValues.equipmentId,
      infoType: formValues.infoType,
      telephone: formValues.telephone,
      beginTime: formValues.timeRange ? formValues.timeRange[0]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: formValues.timeRange ? formValues.timeRange[1]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      pageNum: 1,
    })
  }

  const jump2chargeOrderDetailPage = (record: BigChargeOrder) => {
    jump2target(`/companyOrder/detail?orderId=${record.id}&infoType=${record.orgName ? 3 : 1}`, {needRefresh: true})
  }

  const columns: ColumnsType<BigChargeOrder> = [
    {
      title: '订单信息',
      key: 'orderInfo',
      width: 180,
      render: (_, record) => {
        return <ColumnDesc
          list={[
            {label: '订单号', value: record.id},
            {label: '充电类型', value: record.orgName ? '企业充电' : '个人充电'},
          ]}
        />
      }
    },
    {
      title: '电站信息',
      key: 'stationInfo',
      width: 180,
      render: (_, record) => {
        return <ColumnDesc
          list={[
            {label: '电站名称', value: record.stationName},
            {label: '枪编号', value: record.stubId},
            {label: '设备类型', value: record.stubType ? (record.stubType === EquipmentType.直流 ? '直流' : '交流') : '--'},
          ]}
        />
      }
    },
    {
      title: '用户信息',
      key: 'userInfo',
      width: 180,
      render: (_, record) => {
        return <ColumnDesc
          list={[
            {label: '企业名称', value: record.orgName || '--'},
            {label: '车牌号', value: record.carPlat || '--'},
            {label: '用户昵称', value: record.nickname},
            {label: '手机号', value: record.telephone},
          ]}
        />
      }
    },
    {
      title: '充电信息',
      key: 'chargeInfo',
      width: 180,
      render: (_, record) => {
        let status: React.ReactNode = '--'
        switch (record.status) {
          case BigChargeOrderStatus.进行中: status = <Badge status="processing" text="充电中" />; break
          case BigChargeOrderStatus['完成充电(待支付)']:
          case BigChargeOrderStatus['完成充电(已支付)']: status = <Badge status="success" text="充电完成" />; break;
        }
        return <ColumnDesc
          list={[
            {label: '充电状态', value: status},
            {label: '开始时间', value: record.beginTime},
            {label: '结束时间', value: record.endTime || '--'},
            {label: '初始SOC', value: `${record.socBegin}%`},
            {label: '结束SOC', value: `${record.socEnd}%`},
            {label: '停止原因', value: record.endName || '--'},
          ]}
        />
      }
    },
    {
      title: '付款详情',
      key: 'payInfo',
      width: 180,
      render: (_, record) => {
        let status: React.ReactNode = '--'
        switch (record.status) {
          case BigChargeOrderStatus.进行中: break
          case BigChargeOrderStatus['完成充电(待支付)']: status = <Badge status="error" text="待支付" />; break;
          case BigChargeOrderStatus['完成充电(已支付)']: status = <Badge status="success" text="已支付" />; break;
        }
        return <ColumnDesc
          labelWidth={92}
          list={[
            {label: '订单电量', value: record.electric},
            {label: '订单原价金额', value: parseFloat((record.electricFee + record.serviceFee).toFixed(2))},
            {label: '基础电费', value: record.electricFee},
            {label: '服务费', value: record.serviceFee},
            {label: '订单实付金额', value: record.realPay},
            {label: '支付状态', value: status},
            {label: '支付时间', value: record.paymentTime || '--'},
            {label: '支付方式', value: record.payType === BigChargeOrderPayType.企业余额 ? '企业余额' : '个人余额'},
          ]}
        />
      }
    },
    {
      title: '操作',
      key: 'operation',
      width: 80,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <a onClick={() => jump2chargeOrderDetailPage(record)}>订单详情</a>
        </Space>
      }
    }
  ]

  useEffect(() => {
    if (props.params.orderId) {
      searchForm.setFieldsValue({
        id: props.params.orderId
      })
      onFinish({id: props.params.orderId})
    } else if (props.params.sKey) {
      const _paramsStr = sessionStorage.getItem(props.params.sKey.split('___')[0])
      if (_paramsStr) {
        const _params = JSON.parse(_paramsStr)
        let __params: any = undefined
        if (props.params.sKey.startsWith('_searchParams_stationReport')) {
          __params = {
            station: [{
              id: _params.stationId,
              name: _params.stationName,
            }],
            timeRange: [dayjs(_params.beginTime), dayjs(_params.endTime)],
          }
        } else if (props.params.sKey.startsWith('_searchParams_stubReport')) {
          __params = {
            station: [{
              id: _params.stationId,
              name: _params.stationName,
            }],
            equipmentId: _params.equipmentId,
            timeRange: [dayjs(_params.beginTime), dayjs(_params.endTime)],
          }
        }
        if (__params) {
          searchForm.setFieldsValue(__params)
          onFinish(__params)
        }
      }
    }
  }, [props.params.orderId, props.params.sKey, props.params.from])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchBigChargeOrderForm' form={searchForm} onFinish={onFinish} initialValues={{timeRange: [dayjs().subtract(31, 'day'), dayjs()]}}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='订单号' name='id'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='订单状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(BigChargeOrderStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='场站ID' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='桩编号' name='equipmentId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='枪编号' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='车牌号' name='carPlat'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='vin码' name='vin'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='充电类型' name='infoType'>
                  <Select placeholder='请选择' options={enum2options(BigChargeOrderInfoType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='用户手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label='充电时间' name='timeRange'>
                  <DatePicker.RangePicker showTime style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<BigChargeOrder>
          rowKey='id'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default BigChargeOrderPage;
